import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.File;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.swing.JOptionPane;
import JavaBean.User;
/**
 * @author Sai
 * Created by Sai on 2019-03-03.
 */
@WebServlet(urlPatterns = {"/LOGIN"})
public class LOGIN extends HttpServlet {

    @Override

    protected void service(HttpServletRequest request, HttpServletResponse response) throws  IOException {
        try {
            int flag=0;
            String name= request.getParameter("username");
            String password=request.getParameter("password1");
            Connection connection = (Connection) getServletContext().getAttribute("connection");
            Statement statement = connection.createStatement();
            ResultSet resultSet = statement.executeQuery("select * from USER");
            while(resultSet.next()){
                if(resultSet.getString("NAME").equals(name)){
                    User user= new User(resultSet.getString("NAME"),resultSet.getString("EMAIL"),resultSet.getString("PASSWORD"),resultSet.getString("IMG"),resultSet.getString("SNO"));
                    request.getSession().setAttribute("user",user);
                    flag=1;
                }
            }
            if(flag==1)
                response.sendRedirect("/UserPage.jsp");
            else{
                JOptionPane.showMessageDialog(null, "账号密码错误", "请重新登录", JOptionPane.ERROR_MESSAGE);
                response.sendRedirect("/Loging.jsp");
            }
        }
        catch(SQLException e){
            response.sendRedirect("/error.jsp");
            e.printStackTrace();
        }

    }
}
